import { Component, OnInit } from '@angular/core';
import { CrisisService } from "./crisis.service";
import { RouterModule, Routes, ActivatedRoute, Router, ParamMap } from '@angular/router';
import { Crisis } from "./mock-crisis";

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'app-crisis-list',
  template: `
      <ul class="items">
      <li *ngFor="let crisis of crises | async">
        <a [routerLink]="[crisis.id]"
          [class.selected]="isSelected(crisis)">
          <span class="badge">{{ crisis.id }}</span>
          {{ crisis.name }}
        </a>
      </li>
    </ul>

    <router-outlet></router-outlet>
  `,
  styles: []
})
export class CrisisListComponent implements OnInit {
  crisis: Crisis;
  crises: Observable<Crisis[]>;
  selectedId: number;

  constructor(
    private service: CrisisService,
    private route: ActivatedRoute,
    private router: Router
  ) { }

  ngOnInit() {
    this.crises = this.route.paramMap
      .switchMap((params: ParamMap) => {
        // (+) before `params.get()` turns the string into a number
        this.selectedId = +params.get('id');
        return this.service.getcrisis();
      });
  }

  onSelect(crisis: Crisis) {
    this.selectedId = crisis.id;
    // Navigate with relative link
    this.router.navigate([crisis.id], { relativeTo: this.route });
  }

  isSelected(crisis: Crisis) { return crisis.id === this.selectedId; }
}
